package cfgs.gestudent.dao.connexio;

import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

import javax.swing.JOptionPane;

import cfgs.gestudent.models.EntitatSerivodBBDD;
import cfgs.gestudent.preferencies.ConfiguracionsIdiomes;
import cfgs.gestudent.preferencies.PreferenciesServidor;

public class ConnexioDB {
	
	
	
	public static final Connection getConnexio(){
		
		ConfiguracionsIdiomes conf = new ConfiguracionsIdiomes();
		ResourceBundle rb = conf.getIdioma();
		
		Connection connexio = null;
		PreferenciesServidor ps = new PreferenciesServidor();
		EntitatSerivodBBDD esbd = ps.getParametre();
		
		String server = esbd.getServidor();
		String port = esbd.getPort();
		String nameDB = esbd.getNomBD();
		String user = esbd.getUsuari();
		String password = esbd.getPassword();
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
			connexio = DriverManager.getConnection("jdbc:mysql://"+server+":"+port+"/"+nameDB, user, password);
		} catch(SQLException e){
			JOptionPane.showMessageDialog(null, rb.getString("missatgeConexioIncorrecta"), rb.getString("titolConexioIncorrecta"), JOptionPane.ERROR_MESSAGE);
		}catch(ClassNotFoundException e){
			JOptionPane.showMessageDialog(null, rb.getString("missatgeErrorDriver"), rb.getString("titolErrorDriver"), JOptionPane.ERROR_MESSAGE);
		}
		
		return connexio;
		
	}
	
	public int numeroDeFilas(String sql){
		
		Statement st = null;
		ResultSet rs = null;
		int numOfRows = 0;
		try{
			Connection con = ConnexioDB.getConnexio();
			st = con.createStatement();
			rs = st.executeQuery(sql);
			if (rs.last()){
				numOfRows = rs.getRow();
				} else {
				numOfRows = 0;
				}
				rs.first();
				
				rs.close();
				st.close();
				con.close();
		}catch (SQLException e){
			e.printStackTrace();
		}
		return numOfRows;
	}

}
